import { validatenull } from "./validate";
/**
 * 存储localStorage
 */
export const setStore = (params: { name: string; content: unknown; type?: boolean }) => {
  const { name, content, type } = params;
  const obj = {
    dataType: typeof content,
    content: content,
    type: type,
    datetime: new Date().getTime()
  };
  if (type) {
    window.sessionStorage.setItem(name, JSON.stringify(obj));
  } else {
    window.localStorage.setItem(name, JSON.stringify(obj));
  }
};
/**
 * 获取localStorage
 */
export const getStore = (params: { name: string; type?: boolean }) => {
  const { name, type } = params;
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  let obj: any = {},
    content;
  obj = window.sessionStorage.getItem(name);
  if (validatenull(obj)) {
    obj = window.localStorage.getItem(name);
  }
  if (validatenull(obj)) {
    return;
  }
  try {
    obj = JSON.parse(obj);
  } catch {
    return obj;
  }
  if (type) {
    return obj;
  }
  if (obj?.dataType === "string") {
    content = obj.content;
  } else if (obj.dataType === "number") {
    content = Number(obj.content);
  } else if (obj.dataType === "boolean") {
    /* eslint-disable-next-line */
    content = eval(obj.content);
  } else if (obj.dataType === "object") {
    content = obj.content;
  }
  return content;
};
/**
 * 删除localStorage
 */
export const removeStore = (params: { name: string; type?: boolean }) => {
  const { name, type } = params;
  if (type) {
    window.sessionStorage.removeItem(name);
  } else {
    window.localStorage.removeItem(name);
  }
};
/**
 * 获取全部localStorage
 */
export const getAllStore = (params: { type?: boolean }) => {
  const list: unknown[] = [];
  const { type } = params;
  if (type) {
    for (let i = 0; i <= window.sessionStorage.length; i++) {
      const key = window.sessionStorage.key(i);
      if (key) {
        list.push({
          name: key,
          content: getStore({
            name: key,
            type: true
          })
        });
      }
    }
  } else {
    for (let i = 0; i <= window.localStorage.length; i++) {
      const key = window.localStorage.key(i);
      if (key) {
        list.push({
          name: key,
          content: getStore({
            name: key
          })
        });
      }
    }
  }
  return list;
};
/**
 * 清空全部localStorage
 */
export const clearStore = (params: { type?: boolean }) => {
  const { type } = params;
  if (type) {
    window.sessionStorage.clear();
  } else {
    window.localStorage.clear();
  }
};
